package com.kurumi.util.thread;

import java.awt.image.BufferedImage;
import java.io.File;
import java.util.List;
import java.util.concurrent.CountDownLatch;

import javax.imageio.ImageIO;

import org.apache.pdfbox.rendering.PDFRenderer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.kurumi.util.ExceptionUtil;


public class PdfRenderThread implements Runnable{
	
	private static Logger log = LoggerFactory.getLogger(PdfRenderThread.class);
	
	private PDFRenderer render = null;
	private List<Integer> pageList = null;
	private List<String> fileNameList = null;
	private String imagePath;
	private CountDownLatch latch;
	private String pdfPath;
	
	public PdfRenderThread(PDFRenderer render, List<Integer> pageList,List<String> fileNameList, String imagePath, String pdfPath,  CountDownLatch latch) {
		this.render = render;
		this.pageList = pageList;
		this.fileNameList = fileNameList;
		this.imagePath = imagePath;
		this.latch = latch;
		this.pdfPath = pdfPath;
	}

	public void run(){
				String fileName = null;
				
				for (int i = 0; i < pageList.size(); i++) {
					int pageNum = pageList.get(i);
					try {
						BufferedImage image = render.renderImageWithDPI(pageNum, 197f);
						fileName = fileNameList.get(i);
						ImageIO.write(image, "png", new File(imagePath + fileName));
						image.flush();
						image=null;
						System.out.println("pdf to img " + fileName);
					} catch (Exception e) {
						log.error("pdf转图片异常: pdf本地路径={}, 转换后的图片保存路径={},异常={}",
								pdfPath, fileName, ExceptionUtil.getStackTrace(e));
					} 
				}
				latch.countDown();
	}

	
	
	
}
